<?php

const ONETHINK_VERSION    = '1.0.131218';
const ONETHINK_ADDON_PATH = './Addons/';

/*批量修改
     *  @param $saveWhere ：想要更新主键ID数组
     *  @param $saveData    ：想要更新的ID数组所对应的数据
     *  @param $tableName  : 想要更新的表明
     *  @param $saveWhere  : 返回更新成功后的主键ID数组
     * */
function saveAll($saveWhere,&$saveData,$tableName){
    if($saveWhere==null||$tableName==null)
        return false;
    //获取更新的主键id名称
    $key = array_keys($saveWhere)[0];
    //获取更新列表的长度
    $len = count($saveWhere[$key]);
    $flag=true;
    $model = isset($model)?$model:M($tableName);
    //开启事务处理机制
    $model->startTrans();
    //记录更新失败ID
    $error=[];
    for($i=0;$i<$len;$i++){
        //预处理sql语句
        $isRight=$model->where($key.'='.$saveWhere[$key][$i])->save($saveData[$i]);
        if($isRight==0){
            //将更新失败的记录下来
            $error[]=$i;
            $flag=false;
        }
        //$flag=$flag&&$isRight;
    }
    if($flag ){
        //如果都成立就提交
        $model->commit();
        return $saveWhere;
    }elseif(count($error)>0&count($error)<$len){
        //先将原先的预处理进行回滚
        $model->rollback();
        for($i=0;$i<count($error);$i++){
            //删除更新失败的ID和Data
            unset($saveWhere[$key][$error[$i]]);
            unset($saveData[$error[$i]]);
        }
        //重新将数组下标进行排序
        $saveWhere[$key]=array_merge($saveWhere[$key]);
        $saveData=array_merge($saveData);
        //进行第二次递归更新
        saveAll($saveWhere,$saveData,$tableName);
        return $saveWhere;
    }
    else{
        //如果都更新就回滚
        $model->rollback();
        return false;
    }
}
//字符串截取
function subtext($text, $length)
{
    if(mb_strlen($text, 'utf8') > $length){
        return mb_substr($text, 0, $length, 'utf8').'...';
    }else{
        return $text;
    }
}
//字符串截取
function cutstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr"))
    {
        return mb_substr($str, $start, $length, $charset);
    }
    elseif(function_exists('iconv_substr')) {
        return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return strip_tags($slice);
}

//密码加密
function mymd5($password){
	$jmpassword = md5(md5($password));
	return $jmpassword;
}


//格式化数组
function p($arr){
    echo '<pre>';
    print_r($arr);exit;
    echo '</pre>';
}


//返回当前分类下的所有子节点

function getCateSon($id,$field){
	
	$data['pid'] = array('eq',$id);
	$data['status'] = array('eq',1);
	
	$category = M('category')->where($data)->select();
	
	$cate_id = twoCodeList($category,$field);
	
	return $cate_id;
	
}

//将二维数组的ID转换成字符串

function twoCodeList($code,$field){

    foreach($code as $k => $v){

        if(!empty($v[$field])){

            if(count($code) == $k+1){

                $vid = $vid.$v[$field];

            }else{

                $vid = $vid.$v[$field].',';

            }

        }
    }
    return $vid;
}


function getgroup($id=UID){
    $auth_group_access=M('auth_group_access')->where('uid='.$id)->find();
    $auth_group=M('auth_group')->find($auth_group_access['group_id']);
    return $auth_group['title'];
}
function getgroupid($id){
    $auth_group_access=M('auth_group_access')->where('uid='.$id)->find();
    return $auth_group_access['group_id'];
}


//返回头像地址
function picture($id){
	
	$picture = M('picture')->find($id);
	
	if(empty($picture['path'])){
		
		return '/Public/Home/images/mr.jpg';
		
	}else{
       return $picture['path']; 
    }
}


//日期转换	
function toDate($time, $format = 'Y-m-d') {
	if (empty ( $time )) {
		return '';
	}
	$format = str_replace ( '#', ':', $format );
	return date ($format, $time );
}

//返回某表字段

function modelField($id,$model,$field){
	
	$vo = M($model)->find($id);
	
	return $vo[$field];
	
}

//返回下载文件的路径
function fileurl($id){
    $files = M('file')->where('id='.$id)->find();
    if($files){
        $str = '/Uploads/Download/'.$files[savepath].$files[savename];
        return $str;
    }else{
        return '';
    }
}

/**
 *
 * 通过 Thinkphp 的魔术方法 判断 推荐码是否已经存在返回 未被占用的随机码
 *
 *
 * */
function digCode($data,$len){
	$code = create_code($len);

	$row = $data->getByRecomendUser($code);

	if($row > 0){
		$code = digCode($data, $len);
	}

	return $code;

}
/**
 * 生成指定长度 的随机码中间加了判断，如果生成的
 * 码少于指定长度 就递归生成直至成功
 * 测试阶段没发现 有多于指定长度字符串的出现
 *
 *
 *
 * **/
function create_code($length = 4) {

	$length = intval($length);

	$length = $length-1;
	$min = pow(10,($length - 1));
	$max = pow(10, ($length + 1));

	$ret = rand($min, $max);
	//return $length+1;
	if(strlen($ret) != $length+1){
		$ret = create_code($length+1);
			
	}

	return $ret;
}


/**
 * 根据用户ID获取用户昵称
 * @param  integer $uid 用户ID
 * @return string       用户昵称
 */
function get_nickname($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }

    /* 获取缓存数据 */
    if(empty($list)){
        $list = S('sys_user_nickname_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if(isset($list[$key])){ //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $info = M('Member')->field('nickname')->find($uid);
        if($info !== false && $info['nickname'] ){
            $nickname = $info['nickname'];
            $name = $list[$key] = $nickname;
            /* 缓存用户 */
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_user_nickname_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}


/**
 * 系统公共库文件
 * 主要定义系统公共函数库
 */

function  getagebybirthday($birthday){
	$temparr=explode('-',$birthday);
	$nowyear= date('Y',time());
	if(empty($birthday))return 0;
	return $nowyear-$temparr[0];
}

/**
 * 检测用户是否登录
 */
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

/**
 * 检测当前用户是否为管理员
 */
function is_administrator($uid = null){
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 */
function str2arr($str, $glue = ','){
    return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 */
function arr2str($arr, $glue = ','){
    return implode($glue, $arr);
}

/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}


//后台会员加密
function think_ucenter_md5($str, $key = 'ThinkUCenter'){
	return '' === $str ? '' : md5(sha1($str) . $key);
}


/**
 * 系统加密方法
 */
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 */
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 数据签名认证
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
* 对查询结果集进行排序
*/
function list_sort_by($list,$field, $sortby='asc') {
   if(is_array($list)){
       $refer = $resultSet = array();
       foreach ($list as $i => $data)
           $refer[$i] = &$data[$field];
       switch ($sortby) {
           case 'asc': // 正向排序
                asort($refer);
                break;
           case 'desc':// 逆向排序
                arsort($refer);
                break;
           case 'nat': // 自然排序
                natcasesort($refer);
                break;
       }
       foreach ( $refer as $key=> $val)
           $resultSet[] = &$list[$key];
       return $resultSet;
   }
   return false;
}

/**
 * 把返回的数据集转换成Tree
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){
    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
 * 格式化字节大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 设置跳转页面URL
 */
function set_redirect_url($url){
    cookie('redirect_url', $url);
}

/**
 * 获取跳转页面URL
 */
function get_redirect_url(){
    $url = cookie('redirect_url');
    return empty($url) ? __APP__ : $url;
}

/**
 * 处理插件钩子
 */
function hook($hook,$params=array()){
    \Think\Hook::listen($hook,$params);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
    $class = "Addons\\{$name}\\{$name}Addon";
    return $class;
}

/**
 * 获取插件类的配置文件数组
 */
function get_addon_config($name){
    $class = get_addon_class($name);
    if(class_exists($class)) {
        $addon = new $class();
        return $addon->getConfig();
    }else {
        return array();
    }
}

/**
 * 插件显示内容里生成访问插件的url
 */
function addons_url($url, $param = array()){
    $url        = parse_url($url);
    $case       = C('URL_CASE_INSENSITIVE');
    $addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
    $controller = $case ? parse_name($url['host']) : $url['host'];
    $action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

    /* 解析URL带的参数 */
    if(isset($url['query'])){
        parse_str($url['query'], $query);
        $param = array_merge($query, $param);
    }

    /* 基础参数 */
    $params = array(
        '_addons'     => $addons,
        '_controller' => $controller,
        '_action'     => $action,
    );
    $params = array_merge($params, $param); //添加额外参数

    return U('Addons/execute', $params);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i:s'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 根据用户ID获取用户名
 * @param  integer $uid 用户ID
 * @return string       用户名
 */
function get_username($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }

    /* 获取缓存数据 */
    if(empty($list)){
        $list = S('sys_active_user_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if(isset($list[$key])){ //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $User = new User\Api\UserApi();
        $info = $User->info($uid);
        if($info && isset($info[1])){
            $name = $list[$key] = $info[1];
            /* 缓存用户 */
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_active_user_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}


/**
 * 获取分类信息并缓存分类
 * @param  integer $id    分类ID
 * @param  string  $field 要获取的字段名
 * @return string         分类信息
 */
function get_category($id, $field = null){
    static $list;

    /* 非法分类ID */
    if(empty($id) || !is_numeric($id)){
        return '';
    }

    /* 读取缓存数据 */
    if(empty($list)){
        $list = S('sys_category_list');
    }

    /* 获取分类名称 */
    if(!isset($list[$id])){
        $cate = M('Category')->find($id);
        if(!$cate || 1 != $cate['status']){ //不存在分类，或分类被禁用
            return '';
        }
        $list[$id] = $cate;
        S('sys_category_list', $list); //更新缓存
    }
    return is_null($field) ? $list[$id] : $list[$id][$field];
}

/* 根据ID获取分类标识 */
function get_category_name($id){
    return get_category($id, 'name');
}

/* 根据ID获取分类名称 */
function get_category_title($id){
    return get_category($id, 'title');
}

/**
 * 获取文档模型信息
 * @param  integer $id    模型ID
 * @param  string  $field 模型字段
 * @return array
 */
function get_document_model($id = null, $field = null){
    static $list;

    /* 非法分类ID */
    if(!(is_numeric($id) || is_null($id))){
        return '';
    }

    /* 读取缓存数据 */
    if(empty($list)){
        $list = S('DOCUMENT_MODEL_LIST');
    }

    /* 获取模型名称 */
    if(empty($list)){
        $map   = array('status' => 1, 'extend' => 1);
        $model = M('Model')->where($map)->field(true)->select();
        foreach ($model as $value) {
            $list[$value['id']] = $value;
        }
        S('DOCUMENT_MODEL_LIST', $list); //更新缓存
    }

    /* 根据条件返回数据 */
    if(is_null($id)){
        return $list;
    } elseif(is_null($field)){
        return $list[$id];
    } else {
        return $list[$id][$field];
    }
}

/**
 * 解析UBB数据
 */
function ubb($data){
    //TODO: 待完善，目前返回原始数据
    return $data;
}

/**
 * 记录行为日志，并执行该行为的规则
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null){

    //参数检查
    if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }

    //查询行为,判断是否执行
    $action_info = M('Action')->getByName($action);


    if($action_info['status'] != 1){
        return '该行为被禁用或删除';
    }

    //插入行为日志
    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(get_client_ip());
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;

    //解析日志规则,生成日志备注
    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   NOW_TIME;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] =   str_replace($match[0], $replace, $action_info['log']);
        }else{
            $data['remark'] =   $action_info['log'];
        }
    }else{
        //未定义日志规则，记录操作url
        $data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];
    }

    M('ActionLog')->add($data);

    if(!empty($action_info['rule'])){
        //解析行为
        $rules = parse_action($action, $user_id);

        //执行行为
        $res = execute_action($rules, $action_info['id'], $user_id);
    }
}

/**
 * 解析行为规则
 */
function parse_action($action = null, $self){
    if(empty($action)){
        return false;
    }

    //参数支持id或者name
    if(is_numeric($action)){
        $map = array('id'=>$action);
    }else{
        $map = array('name'=>$action);
    }

    //查询行为信息
    $info = M('Action')->where($map)->find();
    if(!$info || $info['status'] != 1){
        return false;
    }

    //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
    $rules = $info['rule'];
    $rules = str_replace('{$self}', $self, $rules);
    $rules = explode(';', $rules);
    $return = array();
    foreach ($rules as $key=>&$rule){
        $rule = explode('|', $rule);
        foreach ($rule as $k=>$fields){
            $field = empty($fields) ? array() : explode(':', $fields);
            if(!empty($field)){
                $return[$key][$field[0]] = $field[1];
            }
        }
        //cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
        if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){
            unset($return[$key]['cycle'],$return[$key]['max']);
        }
    }

    return $return;
}

/**
 * 执行行为
 * @param array $rules 解析后的规则数组
 * @param int $action_id 行为id
 * @param array $user_id 执行的用户id
 * @return boolean false 失败 ， true 成功
 * @author huajie <banhuajie@163.com>
 */
function execute_action($rules = false, $action_id = null, $user_id = null){
    if(!$rules || empty($action_id) || empty($user_id)){
        return false;
    }

    $return = true;
    foreach ($rules as $rule){

        //检查执行周期
        $map = array('action_id'=>$action_id, 'user_id'=>$user_id);
        $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
        $exec_count = M('ActionLog')->where($map)->count();
        if($exec_count > $rule['max']){
            continue;
        }

        //执行数据库操作
        $Model = M(ucfirst($rule['table']));
        $field = $rule['field'];
        $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

        if(!$res){
            $return = false;
        }
    }
    return $return;
}

//基于数组创建目录和文件
function create_dir_or_files($files){
    foreach ($files as $key => $value) {
        if(substr($value, -1) == '/'){
            mkdir($value);
        }else{
            @file_put_contents($value, '');
        }
    }
}

if(!function_exists('array_column')){
    function array_column(array $input, $columnKey, $indexKey = null) {
        $result = array();
        if (null === $indexKey) {
            if (null === $columnKey) {
                $result = array_values($input);
            } else {
                foreach ($input as $row) {
                    $result[] = $row[$columnKey];
                }
            }
        } else {
            if (null === $columnKey) {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row;
                }
            } else {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row[$columnKey];
                }
            }
        }
        return $result;
    }
}

/**
 * 获取表名（不含表前缀）
 */
function get_table_name($model_id = null){
    if(empty($model_id)){
        return false;
    }
    $Model = M('Model');
    $name = '';
    $info = $Model->getById($model_id);
    if($info['extend'] != 0){
        $name = $Model->getFieldById($info['extend'], 'name').'_';
    }
    $name .= $info['name'];
    return $name;
}


/**
 * 调用系统的API接口方法（静态方法）
 */
function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'Common';
    $callback  = $module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}

/**
 * 根据条件字段获取指定表的数据
 */
function get_table_field($value = null, $condition = 'id', $field = null, $table = null){
    if(empty($value) || empty($table)){
        return false;
    }

    //拼接参数
    $map[$condition] = $value;
    $info = M(ucfirst($table))->where($map);
    if(empty($field)){
        $info = $info->field(true)->find();
    }else{
        $info = $info->getField($field);
    }
    return $info;
}


/**
 * 获取文档封面图片
 * @param int $cover_id
 * @param string $field
 * @return 完整的数据  或者  指定的$field字段值
 * @author huajie <banhuajie@163.com>
 */
function get_cover($cover_id, $field = null){
    if(empty($cover_id)){
        return false;
    }
    $picture = M('Picture')->where(array('status'=>1))->getById($cover_id);
    return empty($field) ? $picture : $picture[$field];
}

/**
 * 检查$pos(推荐位的值)是否包含指定推荐位$contain
 */
function check_document_position($pos = 0, $contain = 0){
    if(empty($pos) || empty($contain)){
        return false;
    }

    //将两个参数进行按位与运算，不为0则表示$contain属于$pos
    $res = $pos & $contain;
    if($res !== 0){
        return true;
    }else{
        return false;
    }
}

/**
 * 获取数据的所有子孙数据的id值
 */

function get_stemma($pids,Model &$model, $field='id'){
    $collection = array();

    //非空判断
    if(empty($pids)){
        return $collection;
    }

    if( is_array($pids) ){
        $pids = trim(implode(',',$pids),',');
    }
    $result     = $model->field($field)->where(array('pid'=>array('IN',(string)$pids)))->select();
    $child_ids  = array_column ((array)$result,'id');

    while( !empty($child_ids) ){
        $collection = array_merge($collection,$result);
        $result     = $model->field($field)->where( array( 'pid'=>array( 'IN', $child_ids ) ) )->select();
        $child_ids  = array_column((array)$result,'id');
    }
    return $collection;
}

//获取分类
function getCategorySon($model,$pid){
    $where['status'] = array('eq',1);
    $where['pid']    = array('eq',$pid);
    $list = M($model)->where($where)->order('sort asc,id desc')->select();
    return $list;
}



//时间条件
function timeCondition($start_time,$end_time){
    if($start_time!=''&&$end_time==''){
        $where = array('egt',strtotime($start_time.' 00:00:00'));
    }
    if($start_time==''&&$end_time!=''){
        $where = array('elt',strtotime($end_time.' 23:59:59'));
    }
    if($start_time!=''&&$end_time!=''){
        $where = array(array('egt',strtotime($start_time.' 00:00:00')),array('elt',strtotime($end_time.' 23:59:59'))) ;
    }
    if($start_time==''&&$end_time==''){
        $where = 0;
    }
    return $where;
}

//审核状态
function checkStatus($check_status){

    if($check_status==0){
        return '<font class="no_check" style="color: red;">未审核</font>';
    }else if($check_status==1){
        return '<font>审核成功</font>';
    }else if($check_status==2){
        return '<font style="color: #f3a800;">审核失败</font>';
    }
}

//验证手机号
function isMobileCode($num){
    return preg_match('#^1[\d]{10}$#', $num) ? true : false;
}


/**
 * 获取当前文档的分类
 */
function get_cate($cate_id = null){
    if(empty($cate_id)){
        return '未填写';
    }
    $cate   =   M('Category')->where('id='.$cate_id)->getField('title');
    return $cate;
}
//获取图集
function imgarr($imgarr){

	if(!empty(trim($imgarr))){
		$imgarrse = explode(',',$imgarr);
		foreach ($imgarrse as $ks=>$vs){
			$img[$ks] = picture($vs);
		}
		 return $img;
	}else{
		 return '';
	}
    
   
}

function gongxu($project_id){
    $where['project_id'] = array('eq',$project_id);
    $list = M('project_date')->where($where)->order('id asc')->select();
    $arr = array_column($list,'gongxu_id');
    return $arr;
}

function gongxuId($project_id){
    $where['project_id'] = array('eq',$project_id);
    $list = M('project_date')->where($where)->order('id asc')->select();
    return $list;
}

//查询工序表单条id
function gongxuOne($project_id,$gongxu_id,$type=1){
    $where['project_id'] = array('eq',$project_id);
    if($type==2){
        $where['gongxu_id'] = array('in',$gongxu_id);
        $list = M('project_date')->where($where)->order('id asc')->select();
    }else{
        $list = M('project_date')->where($where)->order('id asc')->find();
    }
    return $list;
}

//工序当前进度
function gongxuJindu($project_id){

    $where['p.project_id'] = array('eq',$project_id);
    $where['p.end_status'] = array('eq',0);
    $info = M('category')->join('bhy_project_date as p on p.gongxu_id=bhy_category.id')->where($where)->order('p.gxsort asc')->field('bhy_category.title,bhy_category.id')->find();
    if(!empty($info)){
        return $info;
    }else{
        return '已完工';
    }
}

//时间区间
function long_time($long_time){
    $dqtime = strtotime(date('Y-m-d 23:59:59'));
    if($long_time==1){
        $oldtime = $dqtime-(3*86400);
    }else if($long_time==2){
        $oldtime = $dqtime-(7*86400);
    }else if($long_time==3){
        $oldtime = $dqtime-(30*86400);
    }else if($long_time==4){
        $oldtime = $dqtime-(60*86400);
    }
    return $oldtime;
}

//查看签到后未发布日志的时间是否超过设定时间
function signOutTime($return_id){
    $where['status'] = array('eq',1);
    $where['return_id'] = array('eq',$return_id);
    $where['flow_type'] = array('eq',2);
    $vo = M('flowater')->where($where)->find();
    if(empty($vo)){
         return '<a href="javascript:;" style="color: red;" onclick="fakuan('.$return_id.')">进行罚款</a>';
    }else{
        return '<a style="color: blue;">已经罚款</a>';
    }
}

//获取我加入的项目id
function myProjectId($uid){
    $where['_string'] = 'FIND_IN_SET('.$uid.',person_id)';
    $where['status'] = array('eq',1);
    $list = M('project')->where($where)->select();
    if(!empty($list)){
        return implode(',',array_column($list,'id'));
    }else{
        return '';
    }
}

/*
*返回时间的差距
*/
function ReTime($time){
    $t=time()-$time;
    $f=array(
        '31536000'=>'年',
        '2592000'=>'月',
        '604800'=>'周',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    );
    foreach ($f as $k=>$v)    {
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}



//当天开始时间和结束时间
function thisDay(){
    $start_time = strtotime(date('Y-m-d 00:00:00'));
    $end_time   = strtotime(date('Y-m-d 23:59:59'));
    $where = array(array('egt',$start_time),array('elt',$end_time));
    return $where;
}
//项目评论数量
function comment_count($project_id){
    $where['project_id'] = array('eq',$project_id);
    $where['status']     = array('eq',1);
    $where['pid']        = array('eq',0);
    $count = M('comment')->where($where)->count();
    return $count;
}

//查询删除的数据
function delMessageId($uid,$type)
{
    $where['uid'] = array('eq', $uid);
    $where['type'] = array('eq', $type);
    $list = M('del_list')->where($where)->select();
    if (!empty($list)) {
        $idarr = implode(',', array_column($list, 'return_id'));
        $where = array('not in', $idarr);
    } else {
        $where = array('gt', 0);
    }
    return $where;
}

//凌凯短信接口
function mobile_msg_api($mobile,$message){
    header("Content-type: text/html; charset=utf-8");
    date_default_timezone_set('PRC'); //设置默认时区为北京时间
    //短信接口用户名 $uid
    $uid = 'CQJS004769';
    //短信接口密码 $passwd
    $passwd = 'nr@123';
    $msg = rawurlencode(mb_convert_encoding($message, "gb2312", "utf-8"));
    $gateway = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID={$uid}&Pwd={$passwd}&Mobile={$mobile}&Content={$msg}&Cell=&SendTime=";
    $result = file_get_contents($gateway);
    return $result;
}


/*
 * 极光推送
 * */
function jpush_send($uid,$content,$m_txt,$app_key,$master_secret,$log=''){

	$push = new \Think\JPushZDY($app_key,$master_secret);
	//$m_txt = '';//推送附加字段的类型对应的内容(可不填) 可能是url,可能是一段文字。
	$m_time = '86400000';//离线保留时间
	
	$alias = array('alias'=>array($uid));

	$receive = $alias;
	$content = $content;
	$message="";//存储推送状态
	$result = $push->push($receive,$content,$m_txt,$m_time);
    return  $result;
}
//查出项目中的业主
function find_house_man($project_id){
    $vo = M('project')->find($project_id);
    $where['id'] = array('in',$vo['person_id']);
    $where['user_type'] = array('eq',5);
    $info = M('usermember')->where($where)->find();
    return $info['mobile'];
}
/**
 * 获取详细地区名称
 * @param int $id
 * @return 区域名称
 * @author yangshuailong <673197841@qq.com>
 */
function detail_area_name($id){
    $area=M('city')->where(array('id'=>$id))->find();
    if($area['level']==3){
        $second_area=M('city')->where(array('id'=>$area['parentid']))->find();
        $first_area=M('city')->where(array('id'=>$second_area['parentid']))->find();
        $area_name=$first_area['areaname'].$second_area['areaname'].$area['areaname'];
        return $area_name;
    }elseif($area['level']==2){
        $first_area=M('city')->where(array('id'=>$area['parentid']))->find();
        $area_name=$first_area['areaname'].$area['areaname'];
        return $area_name;
    }else{
        return $area["areaname"];
    }
}
/**
 * 获取当前地区名称
 * @param int $id
 * @return 区域名称
 * @author yangshuailong <673197841@qq.com>
 */
function now_area_name($id){
    $area=M('city')->where(array('id'=>$id))->find();
    return $area["areaname"];
}

/**
 * 获取单条评论信息
 * @param intger $id 评论id
 * @return  array $comment  信息详情
 * @author yangshuailong <673197841@qq.com>
 */
function comment_info($id){
    $comment=M('goods_comment')->where(array('id'=>$id))->find();
    $shop=M('shop')->where(array('id'=>$comment['shop_id']))->find();
    $comment['shop_name']=$shop['shop_name'];
    $goods=M('goods')->where(array('id'=>$comment['goods_id']))->find();
    $comment['goods_name']=$goods['goods_name'];
    $goods=M('usermember')->where(array('id'=>$comment['uid']))->find();
    $comment['username']=$goods['username'];
    $comment['imgarr']=explode(',',$comment['imgarr']);
    return $comment;
}

/**
 * 获取多条评论信息
 * @param array $id 评论id
 * @return  array $comment  信息详情
 * @author yangshuailong <673197841@qq.com>
 */
function comment_infos($id){
    if($id){
        foreach ($id as $k=>$v){
            $comment=M('goods_comment')->where(array('id'=>$v))->find();
            $comments[$k]['content']=$comment['content'];
            $comments[$k]['type']=$comment['type'];
            $comments[$k]['id']=$v;
        }
    }
    return $comments;
}

/**
 * 获取请求参数
 * @param $pname 参数名
 * @param $msg 错误提示
 * @param $default 默认值，若要设置为空时取默认值，$must设置为false
 * @param $must bool 是否必须
 */
function _param($pname,$msg=null,$default='',$must=true,$is_die=true){
    header("Content-Type: application/json; charset=utf-8");
    $pval=I($pname);
    if($must && empty($pval)){
        if(IS_AJAX || $is_die){//如果是ajax请求，终止，报错
            _internalError($msg);
        }
        _internalError($msg,array(),false);//否则，返回错误信息
    }
    if(!$must && empty($pval)){
        $pval=$default;
    }
    return $pval;
}

/**
 *ajax方式json报错或返回错误信息
 * @param $msg 报错信息
 * @param $data 其他信息数组
 * @param $is_die bool true=终止程序，打印json错误信息；false=返回数组格式错误信息
 */
function _internalError($msg, $data=array(),$is_die=true) {
    header("Content-Type: application/json; charset=utf-8");
    $ret = array(
        'status'=>500,
        'message'=>$msg
    );
    //tom加的---start
    if(count($data)<1){
        $data="";
    }
    //tom加的---start
    $ret['show_data'] = $data;
    if($is_die){
        die(json_encode($ret));
    }
    return $ret;
}
/**
 * ajax方式json打印正确结果或返回正确信息
 */
function _success($msg, $data=array(),$is_die=true,$extra=array()) {
    header("Content-Type: application/json; charset=utf-8");
    $ret = array(
        'status'=>200,
        'message'=>$msg
    );
    //tom加的---start
    if(count($data)<1){
        $data=[];
    }
    //tom加的---start
    $ret['show_data'] = $data;

    foreach ($extra as $k => $v) {
        $ret[$k]=$v;
    }
    if($is_die){
        die(json_encode($ret));
    }
    return $ret;
}

